//package com.yunxin.admin.system.api.system.task;
//
//import cn.hutool.core.collection.ListUtil;
//import cn.hutool.core.date.DateField;
//import cn.hutool.core.date.DateTime;
//import cn.hutool.core.date.DateUtil;
//import cn.hutool.core.util.ObjectUtil;
//import com.fasterxml.jackson.core.type.TypeReference;
//import com.yunxin.common.utils.JacksonUtils;
//import com.yunxin.core.application.admin.team.DistributeDo;
//import com.yunxin.core.application.admin.team.Team;
//import com.yunxin.core.application.admin.team.TeamTaskDistribute;
//import com.yunxin.core.domain.model.order.OrderUserApplyAllocationRepository;
//import com.yunxin.core.infra.persistence.mapper.order.OrderTeamTaskDetailMapper;
//import com.yunxin.core.utils.infra.support.lock.DistributedLock;
//import com.yunxin.core.utils.infra.support.lock.DistributedLockFactory;
//import com.yunxin.core.utils.infra.support.lock.TaskLockKey;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.net.InetAddress;
//import java.util.*;
//
//@Component
//@Slf4j
//@RequiredArgsConstructor
//public class TeamTask {
//
//
//    private final OrderUserApplyAllocationRepository orderUserApplyAllocationRepository;
//
//    private final OrderTeamTaskDetailMapper teamTaskDetailMapper;
//
//    private final DistributedLockFactory distributedLockFactory;
//
//    @Scheduled(cron = "0/10 * * * * *")
//    @Transactional(rollbackFor = Exception.class)
//    public void teamTask() {
//        try {
//            TaskLockKey taskLockKey = TaskLockKey.teamTask_LOCK_KEY;
//            DistributedLock lock = distributedLockFactory.provideDistributedLock(taskLockKey.getPrefix());
//            boolean tryLock = lock.tryLock(taskLockKey.getWaitTime(), taskLockKey.getReleaseTime(), taskLockKey.getTimeUnit());
//            String hostAddress = InetAddress.getLocalHost().getHostAddress();
//            if (tryLock){
//                try {
//                    System.out.println("定时任务开始了 = " + DateUtil.date());
//                    DateTime startTime = DateUtil.date();
//                    startTime.setMutable(false);
//                    DateTime endTime = startTime.offset(DateField.SECOND, 10);
//                    System.out.println(endTime);
//
//                    //查询任务集合
//                    List<DistributeDo> distributeDo = orderUserApplyAllocationRepository.selectTeamTask(startTime, endTime);
//                    for (DistributeDo aDo : distributeDo) {
//                        List<Integer> list = JacksonUtils.X.parse(aDo.getTeamIds(), new TypeReference<>() {
//                        });
//                        Integer teamId = list.get(0);
//                        //判断是否需要分配团队
//                        if (aDo.getTeamCont() > 0) {
//                            teamId = list.get(list.size() - aDo.getTeamCont());
//                            //查询任务详情(查询出未完成的订单)
//                            teamTaskDetailMapper.updateTeamTaskDetailByTaskId(aDo.getId(), teamId);
//
//                            //更新团队下次分发时间,更新计数器
//                            DateTime startTime1 = DateUtil.date();
//                            startTime.setMutable(false);
//                            DateTime endTime1 = startTime1.offset(DateField.HOUR, aDo.getTeamHour());
//                            teamTaskDetailMapper.updateTeamTaskNextTimeForTeam(endTime1, aDo.getId());
//                            //保存任务记录表
//                        }
//
//                        //查询将要分配的订单
//                        List<Long> userIds = teamTaskDetailMapper.selectTeamOfPerson((long) teamId);
//                        List<Long> orderId = teamTaskDetailMapper.selectOrderUserAllocationByTaskId(aDo.getId());
//                        //teamTaskRecordMapper.selectOrderIdsToTeamTaskRecord(startTime,);
//                        //分配订单到人员
//                        if (userIds.isEmpty() || orderId.isEmpty()) {
//                            return;
//                        }
//                        //根据id查询团队
//                        Team team = teamTaskDetailMapper.findTeam((long) teamId);
//                        if (null == team) continue;
//                        //获取当天时间
//                        DateTime start = DateUtil.beginOfDay(new Date());
//                        DateTime end = DateUtil.endOfDay(new Date());
//                        Map<Long, Integer> userCountMap = new HashMap<>();
//                        List<List<Long>> partition = ListUtil.partition(orderId, userIds.size());
//                        for (List<Long> ids : partition) {
//                            for (int i = 0; i < ids.size(); i++) {
//                                //计数统计，将userId和count加入到map
//                                Long userId = userIds.get(i);
//                                Integer count = ObjectUtil.defaultIfNull(userCountMap.get(userId), 0);
//                                count = count + 1;
//                                userCountMap.put(userId, count);
//                                //更新订单详情表
//                                teamTaskDetailMapper.distributeOrderUserApply(ids.get(i), userIds.get(i), startTime);
//                                //更新任务详情表
//                                teamTaskDetailMapper.updateTeamTaskDetail(ids.get(i), userIds.get(i), startTime);
//                            }
//                        }
//
//                        DateTime startTimeOfDay = DateUtil.beginOfDay(new Date());
//                        DateTime endTimeOfDay = DateUtil.endOfDay(new Date());
//                        //查询当天是否已经存在统计表
//                        List<TeamTaskDistribute> teamTaskDistribute = teamTaskDetailMapper.selectTeamCountByTime(startTimeOfDay, endTimeOfDay, userIds);
//                        if (teamTaskDistribute.isEmpty()) {
//                            //为空新建统计 （二次分发）
//                            for (Long userId : userCountMap.keySet()) {
//                                String userName = teamTaskDetailMapper.getUserNameByUserId(userId);
//                                teamTaskDetailMapper.insertIntoForCount(userId, userName, (long) teamId, team.getTeamName(), userCountMap.get(userId), start);
//                            }
//                        } else {
//                            for (Long userId : userCountMap.keySet()) {
//                                //当天已有分配记录，更新
//                                teamTaskDetailMapper.updateForCountTwo(userId, (long) teamId, team.getTeamName(), userCountMap.get(userId), teamTaskDistribute.get(0).getCreatTime());
//                            }
//                        }
//                    }
//
//                }finally {
//                    if (lock.isHeldByCurrentThread()) {
//                        lock.unlock();
//                    }
//                }
//            }else {
//                log.info("ip:{},执行TeamTask任务失败,获取锁失败......", hostAddress);
//            }
//        }catch (Exception e) {
//            log.error("执行TeamTask任务异常", e);
//        }
//    }
//}
//
//
//
//
